package com.css.zfzx.sjcj.modules.hddcB6_GeochemicalProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB6_GeochemicalProjectTable.repository.HddcB6GeochemicalprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB6_GeochemicalProjectTable.repository.HddcB6GeochemicalprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB6_GeochemicalProjectTable.repository.entity.HddcB6GeochemicalprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB6_GeochemicalProjectTable.service.HddcB6GeochemicalprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB6_GeochemicalProjectTable.viewobjects.HddcB6GeochemicalprojecttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB6_GeochemicalProjectTable.viewobjects.HddcB6GeochemicalprojecttableVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-27
 */
@Service
public class HddcB6GeochemicalprojecttableServiceImpl implements HddcB6GeochemicalprojecttableService {

	@Autowired
    private HddcB6GeochemicalprojecttableRepository hddcB6GeochemicalprojecttableRepository;
    @Autowired
    private HddcB6GeochemicalprojecttableNativeRepository hddcB6GeochemicalprojecttableNativeRepository;

    @Override
    public JSONObject queryHddcB6Geochemicalprojecttables(HddcB6GeochemicalprojecttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB6GeochemicalprojecttableEntity> hddcB6GeochemicalprojecttablePage = this.hddcB6GeochemicalprojecttableNativeRepository.queryHddcB6Geochemicalprojecttables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB6GeochemicalprojecttablePage);
        return jsonObject;
    }


    @Override
    public HddcB6GeochemicalprojecttableEntity getHddcB6Geochemicalprojecttable(String id) {
        HddcB6GeochemicalprojecttableEntity hddcB6Geochemicalprojecttable = this.hddcB6GeochemicalprojecttableRepository.findById(id).orElse(null);
         return hddcB6Geochemicalprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB6GeochemicalprojecttableEntity saveHddcB6Geochemicalprojecttable(HddcB6GeochemicalprojecttableEntity hddcB6Geochemicalprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB6Geochemicalprojecttable.setUuid(uuid);
        hddcB6Geochemicalprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB6Geochemicalprojecttable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB6Geochemicalprojecttable.setIsValid("1");
        this.hddcB6GeochemicalprojecttableRepository.save(hddcB6Geochemicalprojecttable);
        return hddcB6Geochemicalprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB6GeochemicalprojecttableEntity updateHddcB6Geochemicalprojecttable(HddcB6GeochemicalprojecttableEntity hddcB6Geochemicalprojecttable) {
        UpdateUtil.copyNullProperties(hddcB6GeochemicalprojecttableRepository.findByUuidAndIsValid(hddcB6Geochemicalprojecttable.getUuid(), "1"), hddcB6Geochemicalprojecttable);
        hddcB6Geochemicalprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB6Geochemicalprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB6GeochemicalprojecttableRepository.save(hddcB6Geochemicalprojecttable);
        return hddcB6Geochemicalprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB6Geochemicalprojecttables(List<String> ids) {
        List<HddcB6GeochemicalprojecttableEntity> hddcB6GeochemicalprojecttableList = this.hddcB6GeochemicalprojecttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB6GeochemicalprojecttableList) && hddcB6GeochemicalprojecttableList.size() > 0) {
            for(HddcB6GeochemicalprojecttableEntity hddcB6Geochemicalprojecttable : hddcB6GeochemicalprojecttableList) {
//                this.hddcB6GeochemicalprojecttableRepository.delete(hddcB6Geochemicalprojecttable);
                hddcB6Geochemicalprojecttable.setIsValid("0");
                hddcB6Geochemicalprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB6Geochemicalprojecttable.setUpdateTime(new Date());
                this.hddcB6GeochemicalprojecttableRepository.save(hddcB6Geochemicalprojecttable);

            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB6GeochemicalprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB6GeochemicalprojecttableEntity> yhDisasterEntities = hddcB6GeochemicalprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB6GeochemicalprojecttableVO> list=new ArrayList<>();
        for (HddcB6GeochemicalprojecttableEntity entity:yhDisasterEntities) {
            HddcB6GeochemicalprojecttableVO yhDisasterVO=new HddcB6GeochemicalprojecttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地球化学探测工程表", "地球化学探测工程表", HddcB6GeochemicalprojecttableVO.class, "地球化学探测工程表.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB6GeochemicalprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB6GeochemicalprojecttableVO.class, params);
            List<HddcB6GeochemicalprojecttableVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB6GeochemicalprojecttableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB6GeochemicalprojecttableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcB6GeochemicalprojecttableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB6GeochemicalprojecttableEntity yhDisasterEntity = new HddcB6GeochemicalprojecttableEntity();
            HddcB6GeochemicalprojecttableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB6Geochemicalprojecttable(yhDisasterEntity);
        }
    }
}


